import request from "../../utils/request";
import westore from "../../utils/westore/westore"

let videoItemHeight = []; //每个视频的距离顶部的高度
let distance = 0; //标记页面是向下还是向上滚动
let currentVideoIndex = 0; //标记当前滚动到那个视频了
let currentPlayVideoIndex = -1;
westore.createPage({
  // 内部私有数据
  isUserLoginEventID: "",
  /**
   * 页面的初始数据
   */
  data: {
    // 判断用户是否登录
    isUserLogin: false,
    // 导航列表数据
    videoNavList: [],
    // 当前点击项
    currentClickNavItemId: "",
    // 视频列表数据
    videoList: [],
    // 当前视频播放ID
    currentVideoItemId: "",
    videoUpdateTime: [], // 记录video播放的时长
    topNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onReady() {
    if (this.data.isUserLogin) {
      this.getVideoNavList();
    }

    this.isUserLoginEventID = westore.addChangeListener("isUserLogin", (isLogin) => {
      console.log("isLogin --->" + isLogin);
      if (isLogin) {
        // 加载视频导航数据
        console.log("加载视频导航数据");
        this.getVideoNavList();
      }
      else {
        // 清空视频页数据
        console.log("清空视频页数据");
        this.setData({
          videoNavList: [],
          currentClickNavItemId: "",
          videoList: [],
        });
      }
    });
  },

  // 页面卸载时触发
  onUnload() {
    westore.removeChangeListener(this.isUserLoginEventID);
  },

  // 返回登录
  gotoLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 加载导航数据
  async getVideoNavList() {
    let navListData = await request.get("video/group/list");
    let videoNavList = navListData.data?.slice(0, 15);
    let firstNavItemID = 'itemid' + videoNavList[0]?.id;

    // 获取视频列表
    await this.getVideoList(firstNavItemID);

    this.setData({
      videoNavList,
      // 默认选中第一个
      currentClickNavItemId: firstNavItemID
    });
  },

  //  处理导航项点击
  videoNavItemTap(event) {
    let groupID = event.target.id;
    this.setData({
      currentClickNavItemId: groupID
    });
    this.getVideoList(groupID);

  },

  // 获取视频列表
  async getVideoList(groupID) {
    // 在scroll-into-view id不能为数字所以添加了itemid前缀
    // 这里需要移除掉
    groupID = groupID.substring(6);
    let videoList = await request.get("video/group", {
      id: groupID
    }, true);

    this.setData({
      videoList: videoList.datas,
      currentVideoItemId: "",
      videoUpdateTime: [],
      topNum: 0
    });

    this.playVideoHandler(`${videoList.datas[0].data.vid}`);
    // 获取视频项顶部间距
    setTimeout(() => {
      wx.createSelectorQuery()
        .selectAll('.video-item')
        .boundingClientRect()
        .exec(rect => {
          rect[0].forEach(item => {
            videoItemHeight.push(item.top);
          });
        }
        );
    }, 0);
  },

  // 播放视频具体
  playVideoHandler(videoID) {
    if (this.data.currentVideoItemId != videoID) {
      this.setData({
        currentVideoItemId: videoID
      });
    }

    // 创建控制video标签的实例对象
    this.videoContext = wx.createVideoContext(videoID);
    // 判断当前的视频之前是否播放过，是否有播放记录, 如果有，跳转至指定的播放位置
    let { videoUpdateTime } = this.data;
    let videoItem = videoUpdateTime?.find(item => item.vid === videoID);
    if (videoItem) {
      this.videoContext.seek(videoItem.currentTime);
    }

    this.videoContext.play();
  },

  // 点击播放视频
  handlePlay(event) {
    // console.log("handlePlay");

    // // 获取当前点击视频的ID
    // let videoID = event.currentTarget.id;
    // this.playVideoHandler(videoID);
  },


  // 视频列表滚动中
  binddragging(event) {
    let scrollTop = event.detail.scrollTop;
    console.log(scrollTop);
    if (scrollTop <= videoItemHeight[0] / 2) {
      currentVideoIndex = 0;
    }

    else if (scrollTop >= distance) {
      //观看下面的视频
      if (currentVideoIndex + 1 < videoItemHeight.length
        && scrollTop >= videoItemHeight[currentVideoIndex] * 0.9) {
        // this.setData({ _index: indexKey + 1 })
        currentVideoIndex += 1;
      }
    } else {
      //观看上面视频
      if (distance - scrollTop < 15) { //每次滚动的距离小于15时不改变  减少setData的次数
        return;
      }
      if (currentVideoIndex - 1 > 0 && scrollTop < videoItemHeight[currentVideoIndex - 1]) {
        currentVideoIndex -= 1
      }
    }
    console.log("indexKey", currentVideoIndex)
    distance = scrollTop;
  },

  // 视频列表滚动结束
  binddragend(event) {
    // 设置新的视频索引
    if (currentVideoIndex != currentPlayVideoIndex) {
      currentPlayVideoIndex = currentVideoIndex;

      let videoItem = this.data.videoList[currentVideoIndex];
      this.playVideoHandler(`${videoItem.data.vid}`);
    }
  },

  // 更新播放进度
  handleTimeUpdate(event) {
    let videoTimeObj = { vid: event.currentTarget.id, currentTime: event.detail.currentTime };
    let { videoUpdateTime } = this.data;

    let videoItem = videoUpdateTime.find(item => item.vid === videoTimeObj.vid);
    if (videoItem) { // 之前有
      videoItem.currentTime = event.detail.currentTime;
    } else { // 之前没有
      videoUpdateTime.push(videoTimeObj);
    }
    // 更新videoUpdateTime的状态
    this.setData({
      videoUpdateTime
    })
  },

  // 视频播放结束调用的回调
  handleEnded(event) {
    // 移除记录播放时长数组中当前视频的对象
    let { videoUpdateTime } = this.data;
    videoUpdateTime.splice(videoUpdateTime.findIndex(item => item.vid === event.currentTarget.id), 1);
    this.setData({
      videoUpdateTime
    })
  },
})